const id = $.trim(MX.getQueryVariable("id"));
if (id == null || id === "null" || !id) {
    LayerUtil.failMsg("未找到标定ID，请重新进入")
}
let windowTs = false;
window.addEventListener('beforeunload', function (event) {
    if (windowTs) {
        event.returnValue = '您确定要离开此页面吗？';
    }
});

// 左侧记录
let left_record = [];
// 实际重量
let actualWeight;
//是否跳过
let skip = false;
// loading
const loading = new Loading();
//执行次数
let runTime = 0;
//标记当前校准记录 是新校准 还是老校准
let cali_type = 0;
let timeer;

let fitting_times = 0;

$(function () {
    Select.builder()
        .url(STATION_JZ_SELECT)
        .initByUrl();
    Request.builder()
        .url(CALIBRATION_RECORD_CHECK + "?id=" + id)
        .isToken(true)
        .callback(function (e) {
            if (e.code === "00000") {
                var data = e.data;
                if (data !== undefined) {
                    if (data.calibrationId !== id) {
                        return false;
                    }
                    var lock = false;
                    var confirm = layer.confirm("查询到该标定有未完成的校准，是否继续上次校准?", {
                        btn: ['确认', '放弃'] //可以无限个按钮
                    }, function () {
                        if (!lock) {
                            lock = true;
                        }
                        var enjoyhint_instance = new EnjoyHint({
                            onSkip: function () {
                                skip = true;
                            }
                        });
                        enjoyhint_instance.run();
                        skip = true;
                        windowTs = true;
                        left_record = JSON.parse(data.caliRecordJson);
                        left_record.forEach(function (item) {
                            var loadingSpinner = $(`<div>${item.name}</div>`).css({
                                'white-space': 'nowrap',
                                'overflow': 'hidden',
                                'animation': 'reveal 2s steps(40) forwards',
                            });
                            $("#record").prepend(loadingSpinner)
                        })
                        if (data.completeStatus === 1) {
                            setTimeout(function () {
                                nextStep()
                            }, 1000)
                        }
                        $("#cali_circle").val(data.circle);
                        $("#cali_speed").val(data.speed);
                        $("#stationId").val(data.stationId);
                        $("#mode").val(data.mode);
                        $("#userBdMinute").val(data.userBdMinute);
                        $("#userBdGram").val(data.userBdGram);
                        fitting_times = data.fittingTimes * 1 - 1;
                        $("#fitting_count").html(fitting_times);
                        cali_type = 1;
                        runTime = data.fittingTimes;
                        layer.close(confirm);
                    }, function () {
                        if (!lock) {
                            lock = true;
                        }
                        Request.builder()
                            .url(CALIBRATION_RECORD_DELETE + "?id=" + id)
                            .isToken(true)
                            .callback(function (e) {
                                layer.close(confirm);
                            }).post();
                        layer.close(confirm);
                    })
                }
            }
            htmlReady();
            calibrationSettings();
        }).get();
})

//完成步骤
function htmlReady() {
    $(document).ready(function () {
        var guideObj = $('.guide-box');
        var tab_pane = guideObj.find('.nav-step-pane');

        guideObj.bootstrapWizard({
            'tabClass': 'nav-step',
            'nextSelector': '[data-wizard="next"]',
            'previousSelector': '[data-wizard="prev"]',
            'finishSelector': '[data-wizard="finish"]',
            'onTabClick': function (e, t, i) {
                return false;
            },
            'onTabShow': function (e, t, i) {
                t.children(":gt(" + i + ").complete").removeClass("complete");
                t.children(":lt(" + i + "):not(.complete)").addClass("complete");
            },
            'onNext': function (tab, navigation, index) {
                var current_index = guideObj.bootstrapWizard('currentIndex');
                var curr_tab = tab_pane.eq(current_index);

                var validator_selector = '[data-provide="validation"]';
                var validator = curr_tab.find(validator_selector).addBack(validator_selector);
                if (validator.length) {
                    var forms = validator.find('input, select, textarea');
                    var validation = true;
                    forms.each(function () {
                        if (this.checkValidity() === false) {
                            guideObj.addClass('was-validated');
                            validation = false;
                        } else {
                            guideObj.removeClass('was-validated');
                        }
                    });
                    if (!validation) {
                        guideObj.addClass('was-validated');
                        return false;
                    }
                }
            },
        });
    });
}

// 校准进入页面
function calibrationSettings() {
    Request.builder()
        .url(CALIBRATION_SETTING_DETAIL)
        .isToken(true)
        .callback(function (e) {
            if (e.code === "00000") {
                $("#cali_circle").val(e.data.circle);
                $("#cali_speed").val(e.data.speed);
            }
        }).get();
    nextStepGuidance()
}

// 下一步引导
function nextStepGuidance() {
    var enjoyhint_instance = new EnjoyHint({
        onSkip: function () {
            skip = true;
        }
    });
    if (!skip) {
        var enjoyhint_script_steps = [{
            'next .next-brand': '欢迎使用校准操作，如果您已经很熟悉此操作，请点击<a style="color: red;">“跳过”<a>。',
            'nextButton': {text: "下一步"},
            'skipButton': {text: "跳过"},
        }, {
            'next #stationId': "请选择校准设备",
            // 'showSkip' : false,
            'showPrev': false,
            'nextButton': {className: "myNext", text: "下一步"},
            'skipButton': {text: "跳过"},
        }, {
            'next #mode': "请选择校准模式",
            // 'showSkip' : false,
            'nextButton': {className: "myNext", text: "下一步"},
            'prevButton': {className: "myPrev", text: "上一步"},
            'skipButton': {text: "跳过"},
            onBeforeStart: function () {
                $(".enjoyhint_prev_btn").addClass("juli");
            },
            onEnd: function () {
                $(".enjoyhint_prev_btn").removeClass('juli');
            }
        }, {
            'next .cali_parameter': "请输入预期的投喂时间投喂重量",
            // 'showSkip' : false,
            'nextButton': {className: "myNext", text: "下一步"},
            'prevButton': {className: "myPrev", text: "上一步"},
            'skipButton': {text: "跳过"},
        }, {
            'click #btn_cali_run': '请点击开始执行，等待设备投喂完成',
            // 'showSkip' : false,
            'timeout': 100,
            'prevButton': {className: "myPrev", text: "上一步"},
            'skipButton': {text: "跳过"},
        }]
        enjoyhint_instance.set(enjoyhint_script_steps);
        enjoyhint_instance.run();
    }
}

$("#btn_cali_run").click(function () {
    var stationId = $("#stationId").val()
    var mode = $("#mode").val()
    if (stationId === undefined || stationId === null || stationId === "") {
        LayerUtil.failMsg("校准设备（养殖池）名称不能为空");
        return false;
    }
    if (mode === undefined || mode === null || mode === "") {
        LayerUtil.failMsg("校准设备（养殖池）名称不能为空");
        return false;
    }
    var data = {
        "calibrationId": id,
        "stationId": stationId,
        "mode": mode,
        "speed": $("#cali_speed").val(),
        "circle": $("#cali_circle").val(),
        "userBdMinute": $("#userBdMinute").val(),
        "userBdGram": $("#userBdGram").val(),
        "type": cali_type
    }
    var lock = false;
    var confirm = LayerUtil.confirm("确认开始执行校准?", function () {
        if (!lock) {
            windowTs = true
            lock = true;
            Request.builder()
                .url(COMPANY_CALIBRATION_JZ_FEED)
                .data(data)
                .isToken(true)
                .callback(function (e) {
                    if (e.code === "00000") {
                        LayerUtil.successMsg("命令已发出~")
                        runTime += 1
                        htmlLeftAnimation("命令已发出~   " + " 第" + runTime + "次执行", true)
                        implementLoading()
                        cali_type = 1;
                    } else {
                        LayerUtil.failMsg(e.msg != null ? e.msg : ERROR_MSG.FAIL)
                    }
                }).post();
            layer.close(confirm);
            $(".mx_validator_button").attr("disabled", false)
        }
    }, function () {
        if (!skip) {
            guide.newGuide();
            var enjoyhint_script_steps = [{
                'click #btn_cali_run': '请点击开始执行，等待设备投喂完成',
                // 'showSkip' : false,
                'timeout': 100,
                'skipButton': {text: "跳过"},
            }]
            guide.implement(enjoyhint_script_steps)
        }
    })
})

function onCaliData(e) {
    if (e.stationId === $("#stationId").val()) {
        if (WS_CMD.JZ_BACK === e.cmd) {
            ws_notice_store("校准设备应答", e.message, false, WS_STATUS.SUCCESS)
            jzData(e)
            return false;
        } else if (WS_CMD.JZ_FEED_REPORT === e.cmd) {
            ws_notice_store("校准设备投喂报告", e.message, false, WS_STATUS.SUCCESS)
            jzData(e)
            return false;
        } else if (WS_CMD.JZ_TIMEOUT === e.cmd) {
            ws_notice_store("校准超时", e.message, false, WS_STATUS.DANGER)
            jzData(e)
            return false;
        }
    }
}

// 步骤二引导
function stepTwo() {
    if (!skip) {
        guide.newGuide();
        var enjoyhint_script_steps = [{
            'next #jz_zhongliang': "请输入实际的投喂重量",
            'nextButton': {className: "myNext", text: "下一步"},
            'prevButton': {className: "myPrev", text: "上一步"},
            'skipButton': {text: "跳过"}
        }]
        if (actualWeight !== undefined && actualWeight != null && actualWeight !== "") {
            enjoyhint_script_steps.push({
                'dblclick #btn_choose': '请选择要进行的操作, <a style="color: red;">点击拟合<a>将再次拟合速度，<a style="color: red;">点击计算标定<a>将完成本次校准操作',
                'showSkip': false,
            })
        } else {
            enjoyhint_script_steps.push({
                'click #speed_count': "点击这个按钮，计算速度",
                // 'showSkip' : false,
                'skipButton': {text: "跳过"},
            })
        }
        guide.implement(enjoyhint_script_steps)
    }
}

//计算速度
$("#speed_count").click(function () {
    var zhongliang = $("#jz_zhongliang").val();
    if (zhongliang == undefined || zhongliang == null || zhongliang == "") {
        LayerUtil.failMsg("实际投喂重量不能为空");
        return false;
    }
    var data = {
        "id": id,
        "quanshu": $("#cali_circle").val(),
        "userBdMinute": $("#userBdMinute").val(),
        "userBdGram": $("#userBdGram").val(),
        "zhongliang": zhongliang,
    }
    Request.builder()
        .url(COMPANY_CALIBRATION_JZ_SPEED_FIRST)
        .data(data)
        .isToken(true)
        .callback(function (e) {
            if (e.code === "00000") {
                LayerUtil.successMsg(ERROR_MSG.SUCCESS)
                htmlLeftAnimation("计算速度成功，校准转速为" + e.data + "(r/min)")
                $("#cali_speed").val(e.data)
                $("#fitting_span").show();
                $("#fitting_count").show();
                $("#btn_fitting").show();
                $("#btn_cali_count").show();
                $("#fitting_count").html(fitting_times)
                $("#speed_count").hide();
                actualWeight = zhongliang
                setTimeout(function () {
                    popUpPrompt()
                }, 500)
                btn_fitting.style.marginRight = "9px"
            } else {
                LayerUtil.failMsg(e.msg != null ? e.msg : ERROR_MSG.FAIL)
            }
        }).post();
})

//弹窗提示
function popUpPrompt() {
    $("#baitSizeCreateDiv").modal()
    calculationSpeed()
}

//弹窗点击继续
$("#go_back_prev").click(function () {
    $("#prev").click();
    setTimeout(function () {
        $("#baitSizeCreateDiv").find(".close").trigger("click");
    }, 100)
})

//弹窗点击完成
$("#cancel").click(function () {
    $("#btn_cali_count").click()
})

//计算速度引导
function calculationSpeed() {
    if (!skip) {
        guide.newGuide();
        var enjoyhint_script_steps = [{
            'dblclick #operate_btn': '是否需要进行再次校准<a style="color: red; font-weight: bold">（多次校准会使结果更加精准）</a><br>如果需要请点击<a style="color: red; font-weight: bold">继续</a>，如不需要点击<a style="color: red; font-weight: bold">完成</a>按钮将进行标定计算',
            'showNext': false,
            'nextButton': {className: "myNext", text: "下一步"},
            'skipButton': {text: "跳过"},
            onBeforeStart: function () {
                $(".enjoyhint").addClass("zindex");
            },
            onEnd: function () {
                $(".enjoyhint").removeClass('zindex');
            }
        }]
        guide.implement(enjoyhint_script_steps)
    }
}

function jumpStep() {
    if (!skip) {
        guide.newGuide();
        var enjoyhint_script_steps = [{
            'click #btn_cali_run': '点击这个按钮，对设备发送投喂指令',
            // 'showSkip' : false,
            'skipButton': {text: "跳过"},
        }]
        guide.implement(enjoyhint_script_steps)
    }
}

//拟合
$("#btn_fitting").click(function () {
    var zhongliang = $("#jz_zhongliang").val();
    if (zhongliang == undefined || zhongliang == null || zhongliang == "") {
        LayerUtil.failMsg("实际投喂重量不能为空");
        return false;
    }
    var data = {
        "id": id,
        "quanshu": $("#cali_circle").val(),
        "userBdMinute": $("#userBdMinute").val(),
        "userBdGram": $("#userBdGram").val(),
        "zhongliang": zhongliang,
    }
    Request.builder()
        .url(COMPANY_CALIBRATION_JZ_SPEED_FITTING)
        .data(data)
        .isToken(true)
        .callback(function (e) {
            if (e.code === "00000") {
                LayerUtil.successMsg(ERROR_MSG.SUCCESS)
                htmlLeftAnimation("拟合成功，校准转速为" + e.data + "(r/min)")
                $("#cali_speed").val(e.data)
                var nihecount = $("#fitting_count").html();
                if (nihecount !== undefined && nihecount !== "") {
                    nihecount = nihecount * 1 + 1;
                }
                $("#btn_fitting").show();
                $("#fitting_count").html(nihecount);
                $("#fitting_span").show();
                $("#btn_cali_count").show();
                $("#speed_count").hide();
                setTimeout(function () {
                    popUpPrompt()
                }, 500)
            } else {
                LayerUtil.failMsg(e.msg != null ? e.msg : ERROR_MSG.FAIL)
            }
        }).post();
})

//计算标定
$("#btn_cali_count").click(function () {
    windowTs = false
    htmlLeftAnimation("计算标定，校准转速为" + $("#cali_speed").val() + "(r/min)")
    var data = {
        "id": id,
        "mode": $("#mode").val(),
        "zhuansu": $("#cali_speed").val(),
        "quanshu": $("#cali_circle").val(),
        "userBdMinute": $("#userBdMinute").val(),
        "userBdGram": $("#userBdGram").val(),
        "zhongliang": $("#jz_zhongliang").val(),
    }
    Request.builder()
        .url(COMPANY_CALIBRATION_JZ_CALI)
        .data(data)
        .isToken(true)
        .callback(function (e) {
            if (e.code === "00000") {
                LayerUtil.successMsg(ERROR_MSG.SUCCESS)
                setTimeout(function () {
                    $("#tableAjaxId").bootstrapTable('refresh', {pageNumber: 1});
                    window.location.href = "/admin/system/calibration/company_calibration.html"
                }, 1000)
            } else {
                LayerUtil.failMsg(e.msg != null ? e.msg : ERROR_MSG.FAIL)
            }
        }).post();
})

// 下一步
function nextStep() {
    $("#btn_next").click();
    if (actualWeight !== undefined && actualWeight != null && actualWeight !== "") {
        btn_cali_run.style.display = "none";
        btn_fitting.style.display = "block";
        fitting_span.style.display = "block";
        fitting_count.style.display = "block";
        btn_cali_count.style.display = "block"
    } else {
        btn_cali_run.style.display = "none";
        speed_count.style.display = "block";
    }
    stepTwo()
}

//上一步
$("#prev").click(function () {
    btn_cali_run.style.display = "block";
    speed_count.style.display = "none"
    btn_fitting.style.display = "none";
    fitting_span.style.display = "none";
    fitting_count.style.display = "none";
    btn_cali_count.style.display = "none"
    jumpStep()
})

function jzData(result) {
    if (result.stationId === $("#stationId").val()) {
        var data = {
            "calibrationId": id
        }
        let content = "";
        if (WS_CMD.JZ_BACK === result.cmd) {
            content = "开始执行投喂，请勿刷新页面";
            LayerUtil.successMsg(content)
            htmlLeftAnimation(content)
            data.content = content;
        } else if (WS_CMD.JZ_FEED_REPORT === result.cmd) {
            content = "执行成功，请称重拟合或再次进行校准";
            LayerUtil.successMsg(content)
            htmlLeftAnimation(content)
            setTimeout(function () {
                nextStep()
            }, 1000)
            data.content = content;
            loading.hide()
        } else if (WS_CMD.JZ_TIMEOUT === result.cmd) {
            content = "设备超时，请检查设备";
            LayerUtil.failMsg(content)
            htmlLeftAnimation(content)
            data.content = content;
            loading.hide()
        }
        let crc = {
            cmd: WS_CMD.UPDATE_CACHE,
            token: Token.get(),
            data: data,
            fingerprint: stationId,
            type: WS_TYPE.CALIBRATION
        }
        wsManager.send(crc);
    }
}

function implementLoading() {
    let options = {
        opacity: '',
        time: 2000,
        title: '请勿刷新或关闭页面',
        fontColor: '',
        fontSize: '',
        loadingColor: '',
        animationTime: '',
        animationW: '',
        animationH: '',
    }
    loading.show(options); // 显示加载动画
}

// 左侧记录动画效果
function htmlLeftAnimation(content, show = false) {
    var timeNow = Date.now();
    var timeStr = DateUtil.changeDateToString(timeNow, DateFormatEnum.YYYY_MM_DD_HH_MM) + ":" + ('0' + new Date().getSeconds()).slice(-2)
    var time = 30;
    var loadingSpinner = $(`<div>${timeStr}&nbsp;&nbsp;${content}</div>`).css({
        'white-space': 'nowrap',
        'overflow': 'hidden',
        'animation': 'reveal 2s steps(40) forwards',
    });
    if (show) {
        timeer = setInterval(function () {
            loadingSpinner.html(`<div>${timeStr}&nbsp;&nbsp;${content}&nbsp;&nbsp;<span id="timeHide">${time}</span></div>`)
            time--
            if (time < 1) {
                var data = {
                    "calibrationId": id
                }
                clearInterval(timeer);
                loadingSpinner.html(`<span>${timeStr}&nbsp;&nbsp;${content}</span>`)
                content = "连接超时，请检查设备";
                LayerUtil.failMsg(content)
                htmlLeftAnimation(content)
                data.content = content;
                let crc = {
                    cmd: WS_CMD.UPDATE_CACHE,
                    token: Token.get(),
                    data: data,
                    fingerprint: stationId,
                    type: WS_TYPE.CALIBRATION
                }
                wsManager.send(crc);
                loading.hide()
            }
        }, 1000);
    } else {
        if (timeer) {
            clearInterval(timeer);
        }
        $("#timeHide").hide()
    }
    $("#record").prepend(loadingSpinner)
}



